package org.cid54.jshopper.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.cid54.jshopper.dao.UserDao;
import org.cid54.jshopper.dao.UserGroupDao;
import org.cid54.jshopper.model.User;
import org.cid54.jshopper.model.UserGroup;
import org.cid54.jshopper.service.UserAndGroupService;
import org.cid54.jshopper.util.Hashher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author fgo
 */
@Service
@Transactional
public class UserAndGroupServiceImpl implements UserAndGroupService {

    @Autowired
    private Hashher hashher;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserGroupDao userGroupDao;

    @Override
    public UserGroup getUserGroupByName(String name) {
        return this.userGroupDao.findByName(name);
    }

    @Override
    public List<User> getUsersByUserGroup(UserGroup userGroup) {
        return this.userDao.findByUserGroup(userGroup);
    }

    @Override
    public List<User> getUsersByUserGroupName(String userGroupName) {
        UserGroup userGroup = this.getUserGroupByName(userGroupName);
        return this.userDao.findByUserGroup(userGroup);
    }

    @Override
    public User getUserByUserName(String userName) {
        return this.userDao.findByName(userName);
    }

    @Override
    public boolean authenticate(String userName, String passwd) {
        User user = this.userDao.findByName(userName);

        if (user == null) {
            return false;
        } else {
            return this.hashher.getHash(passwd, user.getSalt()).equals(user.getPassword());
        }

    }

    @Override
    public List<UserGroup> getUserGroupsByUserName(String userName) {

        User u = this.getUserByUserName(userName);

        return new ArrayList<UserGroup>(u.getUserGroups());

    }

    @Override
    public List<UserGroup> getUserGroupsByUserId(long userId) {

        User u = this.userDao.findById(userId);

        return this.getUserGroupsByUserName(u.getName());

    }

    @Override
    public String getUserNameById(long userId) {
        return this.userDao.findById(userId).getName();
    }

    @Override
    public User getUserByMobileGuid(String guid) {
        return this.userDao.findByGuid(guid);
    }
}
